<?php

class Core_Model_Permission_Role extends Dcmp_Model_Entity {

    public function __construct() {
        parent::__construct();
    }

    public function validate() {
        if ($this->isNew()) {
            if ($this->getTable()->checkExists(array('code' => $this->getCode()))) {
            	throw new Core_Model_Permission_Exception_Role(
            		Core_Model_Permission_Exception_Role::ROLE_REPEATED,
            		Kd_Localize_Helper::__f('permission.message.repeated', '{permission.label.role}', $this->getCode()));
            }
        }
    }
    
    public function getActions(){
    	$idPath = Kd_Util_String::subString($this->getIdPath(), '_').'_';
    	return App::getModel('permission/collection_action')
    			->joinRole()
    			->like('c.id_path', "'".$idPath."%'");
    }
    
    public function getChildRoles(){
    	return App::getModel('permission/collection_role')
    				->filterByIdPath($this->getIdPath());
    }    
    
    public function assignAction($actions, $transaction = NULL){
    	$arr = is_array($actions)? $actions: $actions;
        Kd_Data_Factory::getDeleteDcl()
                ->from('{t}permission_role_action')
                ->where()
                ->eq('role_id', ':roleId:i')
                ->closest()
                ->addParameter('roleId', $this->getId())
                ->setDbDriver($this->getDbDriver($transaction))
                ->execute();
          
		$insert = Kd_Data_Factory::getInsertDcl()
	                ->into('{t}permission_role_action')
	                ->value('role_id', $this->getId())
	                ->value('action_id', ':actionId:i')
	                ->setDbDriver($this->getDbDriver($transaction));   
	                             
		foreach($arr as $actionId){                
	        $insert->addParameter('actionId', $actionId)->execute();
		}
        return $this;
    }
    
    public function setParent($role, $transaction = NULL){
    	$parent = $role;
    	if(!$parent instanceof self){
			$parent = App::getModel('permission/role')->load($role);
    	}
    	
    	$meIdPath = $this->getIdPath();
    	$parentIdPath = $parent->getIdPath();
    	
    	$children = App::getModel('permission/collection_role')
    					->filterByIdPath($meIdPath)
    					->load();
    	
		foreach($children as $child){
			$newIdPath = str_replace($meIdPath, $parentIdPath, $child->getIdPath());
			$child->setIdPath($newIdPath);
			$child->save();
		}    					
    					
    	$this->setParentId($this->getId());
    	$this->setIdPath($parent->getIdPath().$this->getId().'_');
    	$this->save();
    	
    	return $this;    	
    }

    protected function afterInsert($transaction) {
    	if($this->isArrayData('action_ids')){
    		$this->assignAction($this->getActionIds());
    	}
    	$idPath = '';
    	if($this->issetData('parent_id') && $this->getParentId() != 0){
    		$idPath = App::getModel('permission/role')->load($this->getParentId())->getIdPath();
    	}
    	$idPath .= $this->getId().'_';
        Kd_Data_Factory::getUpdateDcl()
                ->into($this->getTable()->getName())
                ->value('id_path', ':idPath:s')
                ->where()->eq('id', ':id:i')->endSelf()
                ->addParameter(array('id' => $this->getId(), 'idPath' => $idPath))
                ->setDbTransaction($transaction)
                ->execute();
    }
    
    protected function afterUpdate($transaction){
        if($this->isArrayData('action_ids')){
    		$this->assignAction($this->getActionIds());
    	}
    	if($this->propertyIsChanged('parent_id')){
    		$this->setParent($this->getParentId(), $transaction);
    	}
    }
    
    protected function initializeTable($table) {
        $table->setName('{t}permission_role');
        $table->createColumn('id', 'integer', TRUE, TRUE);
        $table->createColumn('name');
        $table->createColumn('code')->setUpdateable(FALSE);
        $table->createColumn('status')->setDefaultValue('enabled');
        $table->createColumn('level', 'integer')->setDefaultValue(1);
        $table->createColumn('parent_id', 'integer');
        $table->createColumn('id_path', 'string');
    }

}